<?php

/**
 * @author  PVer
 * @date    2018-5-8 9:25:47
 * @version V1.0
 * @desc    
 */

namespace app\daikuan\controller;

use cmf\controller\AdminBaseController;
use app\daikuan\model\LogisticsModel;
use app\daikuan\model\LogisticsLoanModel;
use app\portal\model\UserModel;
use app\daikuan\model\LogistcsInterestModel;
use think\Validate;
use think\Db;

class LogisticsLoanController extends AdminBaseController {

    public function myindex() {
        $map = array();

        //        table排序
        $order = array();
        $order_type = input('order','desc');
        $order_name = input('order_name','a.Id');
        if (empty($order_name)) {
            $order_name = 'a.ApplyAmount';
        }
        $order = "$order_name $order_type";
        $status = input('status', -1, 'intval');
        if ($status >= 0) {
            $map['a.Status'] = $status;
        }
        $name = input('name');
        if (!empty($name)) {
            $map['b.user_nickname'] = array('like', "%$name%");
        }
        $map["a.LogisticsId"] = cmf_get_current_admin_id();
        $list = db('logistics_loan a')->join(array(array('dk_user b', 'a.LogisticsId=b.id ', 'LEFT')
                    , array('dk_logistics c', 'b.id=c.UserId', 'LEFT'),
                    array('dk_user d', 'd.id=a.CustomerId', 'LEFT')
                ))
                ->field('a.*,b.user_nickname,c.LogisticsType,c.RegistAmount,c.Legal,c.CreateDate LogCreateDate,c.WorkDays,c.LogisticsName,c.CreateDate,d.user_nickname CompanyName,DATEDIFF(now(),a.RepayMentDateTime)  diffday')
                ->where($map)
                ->order($order)
                ->paginate(10, false, ['query' => request()->param(),]);
        //echo db('logistics_loan a')->getLastSql();
        $page = $list->render();
        $this->assign('order', $order_type);
        $this->assign('Status', $status);
        $this->assign('list', $list);
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function index() {
        $map = array();


        //        table排序
        $order = array();
        $order_type = input('order') ?? 'desc';
        $order_name = input('order_name') ?? 'a.Id';
        if (empty($order_name)) {
            $order_name = 'a.ApplyAmount';
        }
        $order = "$order_name $order_type";
        $status = input('status', -1, 'intval');
        if ($status >= 0) {
            $map['a.Status'] = $status;
        }
        $name = input('name');
        if (!empty($name)) {
            $map['b.user_nickname'] = array('like', "%$name%");
        }

        $yuqiday=Db::name('driver_interest')->where('id',1)->value('yujiday');
        //即将逾期查询
        $yuqi=input('yuqi',0);
        if($yuqi){

            $map['a.Status'] = 3;
        }

        $list = db('logistics_loan a')->join(array(array('dk_user b', 'a.LogisticsId=b.id ', 'LEFT')
                    , array('dk_logistics c', 'b.id=c.UserId', 'LEFT'),
                    array('dk_user d', 'd.id=a.CustomerId', 'LEFT')
                ))
                ->field('a.*,b.user_nickname,b.mobile,c.LogisticsType,c.RegistAmount,c.Legal,c.CreateDate LogCreateDate,c.WorkDays,c.LogisticsName,c.CreateDate,d.user_nickname CompanyName,DATEDIFF(now(),a.RepayMentDateTime)  diffday')
                ->where($map)
                ->order($order)
                ->paginate(10, false, ['query' => request()->param(),]);
       // echo db('logistics_loan a')->getLastSql();
        $new_list = array();
        $logistcsInterestModel = new LogistcsInterestModel();
        $interes = $logistcsInterestModel->get(1);
        $yq = $interes['overdueInterest'];
        $overdueDay = $interes['overdueDay'];
        foreach ($list as $row) {
            $diffday = $row['diffday'];
            $lixi = 0;
            if ($diffday > 0) {
                $zq = ceil($diffday / $overdueDay);
                $lixi = $yq * $zq * $row['ApplyAmount'] / 100;
                //$lixi = $yq . '-' . $zq . '-' . $row['ApplyAmount'] . '-' . $lixi;
                $row['lixi'] = $lixi;
            } else {
                // $info['diffday'] = 0;
                $row['lixi'] = 0;
            }
            //即将逾期判断
            if($diffday<0) {

                if (abs($diffday) > $yuqiday) {
                } else {

                    if ($row['Status'] == 3) {
                        $row['yuday'] = abs($diffday);
                    }
                }

            }else{
                $row['yuday'] = 0;
            }

            if($yuqi){
                if($diffday<0){
                    if (abs($diffday) > $yuqiday) {
                        unset($row);
                    }
                }else{
                    unset($row);
                }
            }
            if($row) {
                $new_list[] = $row;
            }
        }

        $page = $list->render(10, false, ['query' => request()->param(),]);
        $this->assign('order', $order_type);
        $this->assign('Status', $status);
        $this->assign('list', $new_list);
        $this->assign('page', $page);
        $this->assign('yuqi', $yuqi);
        return $this->fetch();
    }

    public function addloan() {


        $userModel = new UserModel();
        $loglist = $userModel->where("user_category=2")->select();
        $logistcsInterestModel = new LogistcsInterestModel();
        $interest = $logistcsInterestModel->find();
        $this->assign("interest", $interest);
        $this->assign('log_list', $loglist);
        //$this->assign('page', $page);
        return $this->fetch();
    }

    public function addmyloan() {

        $userModel = new UserModel();
        $myinfo = $userModel->where('id', cmf_get_current_admin_id())->find();
        $logistcsInterestModel = new LogistcsInterestModel();
        $map['user_category'] = 4;
        $map['a.dk_status'] =1;
        $list = db('user a ')->join(array(array('dk_liscustomer b', 'a.id=b.UserId', 'LEFT')
        ))
            ->field(' a.id,a.user_nickname,a.user_login,a.dk_status ')
            ->where($map)
            ->paginate();
        if($list){
            $list = $list->toArray()['data'];
        }else{
            $list= array();
        }
        $this->assign("list", $list);
        $interest = $logistcsInterestModel->find();
        $this->assign("myinfo", $myinfo);
        $this->assign("interest", $interest);
        return $this->fetch();
    }

    public function see() {
        $id = input('id');

        $info = db('logistics_loan a')->join(array(array('dk_user b', 'a.LogisticsId=b.id ', 'LEFT')
                    , array('dk_logistics c', 'b.id=c.UserId', 'LEFT'),
                    array('dk_liscustomer d', 'b.id=d.LogisticsId', 'LEFT')
                ))
                ->field('a.*,b.user_nickname,c.LogisticsType,c.RegistAmount,c.Legal,c.CreateDate LogCreateDate,c.WorkDays,c.LogisticsName,c.CreateDate,d.CompanyName,DATEDIFF(now(),a.RepayMentDateTime)  diffday')
                ->where("a.Id=" . $id)
                ->find();


        $diffday = 0;
        if (empty($info)) {
            $this->error("数据错误");
        } else {
            $diffday = $info['diffday'];
        }
        $lixi = 0;
        if ($diffday > 0) {
            $logistcsInterestModel = new LogistcsInterestModel();
            $interes = $logistcsInterestModel->get(1);
            $yq = $interes['overdueInterest'];
            $overdueDay = $interes['overdueDay'];
            $zq = ceil($diffday / $overdueDay);
            $lixi = $yq * $zq * $info['ApplyAmount'] / 100;
            // $lixi = $yq .'-'. $zq .'-'. $info['ApplyAmount'] .'-'.$lixi;
        } else {
            $info['diffday'] = 0;
        }
        $info['lixi'] = $lixi;

        $this->assign('info', $info);
        return $this->fetch();
    }

    public function edit() {
        $id = input('id');

        $info = db('logistics_loan a')->join(array(array('dk_user b', 'a.LogisticsId=b.id ', 'LEFT')
                    , array('dk_logistics c', 'b.id=c.UserId', 'LEFT'),
                    array('dk_liscustomer d', 'b.id=d.LogisticsId', 'LEFT')
                ))
                ->field('a.*,b.user_nickname,c.LogisticsType,c.RegistAmount,c.Legal,c.CreateDate LogCreateDate,c.WorkDays,c.LogisticsName,c.CreateDate,d.CompanyName')
                ->where("a.Id=" . $id)
                ->find();


        if (empty($info)) {
            $this->error("数据错误");
        }
        $this->assign('info', $info);
        return $this->fetch();
    }

    public function addmyloanpost() {
        if ($this->request->isPost()) {
            $validate = new Validate([
                'CustomerId' => 'require',
                'ApplyAmount' => 'require',
                'CargoCode' => 'require',
                'ApplyDateLength' => 'require',
            ]);
            $validate->message([
                'CustomerId.require' => '客户未选择',
                'ApplyAmount.require' => '借款金额未填写',
                'CargoCode.require' => '物流单号未填写',
                'mobile.require' => '手机号码不能为空',
                'ApplyDateLength.require' => '接口款市场未填写'
            ]);
            $data = $this->request->post();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }

            $log=Db::name('logistics')->where('UserId',$data['LogisticsId'])->find();
            $map['Status'] =  array('neq','4');
            $map['LogisticsId'] = $data['LogisticsId'];
            $logistics_loan = Db::name('logistics_loan')->where($map)->field('sum(ApplyAmount) as total_amount')->find();
            $loan_total_money = $logistics_loan['total_amount']+$data['ApplyAmount'];
            $syedu = $log['CanLoanAmount'] - $logistics_loan['total_amount'];
            if($syedu<0){
                $syedu=0;
            }

            if($loan_total_money > $log['CanLoanAmount']){
                $this->error("超过可以贷款的额度,还可以贷款".$syedu."元");
            }

            $data["SeedAmount"] = $data["ReimAmount"];
            $logisticsLoanModel = new LogisticsLoanModel();
            $result = $logisticsLoanModel->save($data);
            if ($result !== false) {
                $this->success("操作成功", url("myindex"));
            } else {
                $this->error("操作失败");
            }
        }
    }

    public function addloanpost() {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data["SeedAmount"] = $data["ReimAmount"];

            $logisticsLoanModel = new LogisticsLoanModel();
            $log=Db::name('logistics')->where('UserId',$data['LogisticsId'])->find();
            $map['Status'] =  array('neq',array('2','4'));
            $map['LogisticsId'] = $data['LogisticsId'];
            $logistics_loan = Db::name('logistics_loan')->where($map)->field('sum(ApplyAmount) as total_amount')->find();
            $loan_total_money = $logistics_loan['total_amount']+$data['ApplyAmount'];
            $syedu = $log['CanLoanAmount'] - $logistics_loan['total_amount'];
            if($syedu<0){
                $syedu=0;
            }
            if($loan_total_money > $log['CanLoanAmount']){
                $this->error("超过可以贷款的额度,还可以贷款".$syedu."元");
            }


            $result = $logisticsLoanModel->save($data);
            if ($result !== false) {
                $this->success("操作成功", url("index"));
            } else {
                $this->error("操作失败");
            }
        }
    }

    public function editPost() {
        if ($this->request->isPost()) {
            $id = input('Id');
            $data = input('post.');
            $result = false;
            $loan = Db::name('logistics_loan')->where('Id',$id)->find();
            if($loan['Status'] !=5){
                $this->error("客户公司没有确认信息，无法审核");
            }
            if (isset($data['audit'])) {
                //发送短信
                $loan = Db::name('logistics_loan')->where('Id',$id)->find();
                $user=Db::name('user')->where('id',$loan['LogisticsId'])->find();
                $nickname= $user['user_nickname'];
                $tpl_value = "#name#=$nickname&#code#=$id";
                $flag = sendcode($user['mobile'],'91658',$tpl_value);

                $arr = array();
                $arr["Status"] = 1;
                $result = model('LogisticsLoan')->save($arr, ['Id' => $id]);
            } elseif (isset($data['refuse'])) {
                $arr = array();
                $arr["Status"] = 2;
                $arr['reason']=$data['reason'];
                $result = model('LogisticsLoan')->save($arr, ['Id' => $id]);
            }
            if ($result !== false) {
                $this->success("操作成功", url("index"));
            } else {
                $this->error("操作失败");
            }
        }
    }

    public function fangkuan() {
        $id = input('id');
        $logistcsInterestModel = new LogistcsInterestModel();
        $interest = $logistcsInterestModel->find();
        $this->assign("interest", $interest);
        $info = db('logistics_loan a')->join(array(array('dk_user b', 'a.LogisticsId=b.id ', 'LEFT')
                    , array('dk_logistics c', 'b.id=c.UserId', 'LEFT'),
                    array('dk_liscustomer d', 'b.id=d.LogisticsId', 'LEFT')
                ))
                ->field('a.*,b.user_nickname,c.LogisticsType,c.RegistAmount,c.Legal,c.CreateDate LogCreateDate,c.WorkDays,c.LogisticsName,c.CreateDate,d.CompanyName')
                ->where("a.Id=" . $id)
                ->find();
        if (empty($info)) {
            $this->error("数据错误");
        }
        $this->assign('info', $info);
        return $this->fetch();
    }

    public function fangkuanPost() {
        if ($this->request->isPost()) {
            $id = input('Id');
            $data = input('post.');
            $result = false;
            if (isset($data['fangkuan'])) {
                $arr = array();
                $arr["Status"] = 3;
                $arr["FangkuanDate"] = $data['FangkuanDate'];
                $arr["RealDateLength"] = $data['RealDateLength'];
                $arr["RealAmount"] = $data['RealAmount'];
                $arr["serviceCharge"] = $data['serviceCharge'];
                $arr["RepayMentDateTime"] = $data['RepayMentDateTime'];
                $arr["ReimAmount"] = $data['ReimAmount'];
                $arr["Interest"] = $data['Interest'];
                $arr["SeedAmount"] = $data['ReimAmount'];
                $result = model('LogisticsLoan')->save($arr, ['Id' => $id]);
            }
            if ($result !== false) {
                $this->success("操作成功", url("index"));
            } else {
                $this->error("操作失败");
            }
        }
    }

    public function getCustomerByName() {
        $data = input('post.');
        $map = array();
        $map['user_category'] = 4;
        $name = input('UserName');
        if (!empty($name)) {
            $map['user_nickname'] = array('like', "%$name%");
        }
        $userModel = new UserModel();
        $result = $userModel
                ->where($map)
                ->select();
        $arr = array();
        foreach ($result as $row) {
            $arr[] = $row['user_nickname'];
        }

        return $result;
    }

    public function getUserByName() {
        $data = input('post.');
        $map = array();
        $map['user_category'] = 2;
        $name = input('UserName');
        if (!empty($name)) {
            $map['user_nickname'] = array('like', "%$name%");
        }
        $userModel = new UserModel();
        $result = $userModel
                ->where($map)
                ->select();
        //$result = model('Crop')->field('cropname')->select();
        $arr = array();
        foreach ($result as $row) {
            $arr[] = $row['user_nickname'];
        }

        return $result;
    }

    /**
     * 发送短信
     */
    public function sendmsg(){
        $data = input('post.');
        $id =input('Id');
        $yuday =input('yuday');
        $phone =input('phone');
        $nickname=input('nickname');
        $tpl_value = "#name#=$nickname&#code#=$id&#day#=$yuday";
        $flag = sendcode($phone,'91661',$tpl_value);
        if($flag){
            $this->success("发送成功", url("index"));
        }else{
            $this->error("发送失败");
        }

    }

}
